package com.enlighten.aio.td.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.enlighten.aio.db.Enum.OrderStatus;
import com.enlighten.aio.db.Enum.PaymentStatus;
import com.enlighten.aio.db.mapper.OrderItemMapper;
import com.enlighten.aio.db.mapper.OrderMapper;
import com.enlighten.aio.db.mapper.PaymentMapper;
import com.enlighten.aio.db.model.Order;
import com.enlighten.aio.db.model.OrderExample;
import com.enlighten.aio.db.model.OrderItem;
import com.enlighten.aio.db.model.OrderItemExample;
import com.enlighten.aio.db.model.Payment;
import com.enlighten.aio.db.model.PaymentExample;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author Henry
 * @since 2018-07-28
 */
public abstract class AbstractTdPaymentService {
	Logger logger = LoggerFactory.getLogger(AbstractTdPaymentService.class);

	@Resource
	PaymentMapper paymentMapper;
	@Resource
	OrderMapper orderMapper;
	@Resource
	OrderItemMapper orderItemMapper;
	
	
	public void update4ConfirmPay(String orderId, String tradeNo, String payVendor, String payMethod, Date now) {
		PaymentExample ex = new PaymentExample();
		ex.or().andOrderIdEqualTo(orderId);
		List<Payment> list = paymentMapper.selectByExample(ex);
		if(list.isEmpty()) {
			logger.debug(">>>> Payment is Empty <<<<");
		}
		Payment pay = list.get(0);
		pay.setStatus(PaymentStatus.PAID.getCode());
		pay.setTransactionNo(tradeNo);
		pay.setPayMethod(payMethod);
		pay.setPayVendor(payVendor);
		pay.setPayTime(now);
		pay.setUpdateDate(now);
		paymentMapper.updateByPrimaryKeySelective(pay);
		logger.info(">>>> update payment as paid: {}", JSON.toJSONString(pay));

		OrderExample oex = new OrderExample();
		List<Order> olist = orderMapper.selectByExample(oex);
		if(olist.isEmpty()) {
			logger.debug(">>>> Order is Empty <<<<");
		}
		Order order = olist.get(0);
		order.setState(OrderStatus.PAID.getCode());
		order.setPayTime(now);
		order.setUpdateDate(now);
		orderMapper.updateByPrimaryKeySelective(order);
		logger.info(">>>> update order as paid: {}", JSON.toJSONString(order));
		
		OrderItemExample iex = new OrderItemExample();
		iex.or().andOrderIdEqualTo(orderId);
		List<OrderItem> ilist = orderItemMapper.selectByExample(iex);
		if(ilist.isEmpty()) {
			logger.debug(">>>> Item is Empty <<<<");
		}
		OrderItem item = ilist.get(0);
		item.setStatus(OrderStatus.PAID.getCode());
		item.setUpdateTime(now);
		orderItemMapper.updateByPrimaryKeySelective(item);
		logger.info(">>>> update order item as paid: {}", JSON.toJSONString(item));
	}

	public void update4RefundWithOrderId(Long orderId, Date now) {
		
	}
}
